package services;

import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.APNTemplate;
import com.gexin.rp.sdk.template.LinkTemplate;
import com.gexin.rp.sdk.template.NotificationTemplate;
import dao.AppPush_Repository;
import models.DatabaseExecutionContext;
import models.Truck_P_Entity;
import org.apache.commons.collections.CollectionUtils;
import play.db.jpa.JPAApi;
import vo.TruckInfo_C_Entity;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

import static java.util.concurrent.CompletableFuture.supplyAsync;

public class AppPush_JPA implements AppPush_Repository {


    private final JPAApi jpaApi;
    private final DatabaseExecutionContext executionContext;
    //个推
//    private static String appId = "Tq8WBxhdzxA1Y4qEfkH8U3";
//    private static String appKey = "ZLfN36EojC8QPKMDS6dCG";
//    //    private static String CID = "6545c50c7bd64edb2dfac302feb355df";
//    private static String masterSecret = "VjyLx9dWUm8vv3gP4rwjB5";
//    private static String host = "https://api.getui.com/apiex.htm";

    //ios的token
//    static String token = "";
//                   gps系统
    private static String appId = "KIROOuqzhT6Nj8111ewEg";
    private static String appKey = "5X2CsbRtBK9G62ugQmwmkA";
    private static String masterSecret = "HVXu9hW9e79yls3a191xo7";
    private static String host = "http://sdk.open.api.igexin.com/apiex.htm";
    private static String CID = "4461951513bb5620670cdcdd7fff371a";

    @Inject
    public AppPush_JPA(JPAApi jpaApi, DatabaseExecutionContext executionContext) {
        this.jpaApi = jpaApi;
        this.executionContext = executionContext;
    }

    List<Object> listresult = new ArrayList<Object>();

    public static NotificationTemplate temp(EntityManager em, String getPlateNo, String LastTime) {
        NotificationTemplate template = new NotificationTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 设置通知栏标题与内容

        template.setTitle("温馨提示");
        template.setText(LastTime + "您的车辆" + getPlateNo + "连接断开");
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        // 透传消息设置，1为强制启动应用，客户端接收到消息后就会立即启动应用；2为等待应用启动
        template.setTransmissionType(1);
        template.setTransmissionContent("{'title':'安卓透传标题','content':'安卓透传内容','payload':'安卓透传数据'}");
        return template;
    }


    @Override
    public CompletionStage<String> AppPush(String clientId, String token, String deptId, String mobile) {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {

                String strSql = "EXEC p_GetTruckList @GPSFlag = '" + "1" + "'";
                List<Truck_P_Entity> list = entityManager.createNativeQuery(strSql, Truck_P_Entity.class).getResultList();
//                System.out.println(list);
//                List<UserInfo_T_Entity> listUser=entityManager.createQuery("select u from UserInfo_T_Entity u where u.fdMobile :=mobile").setParameter("mobile",mobile).getResultList();
                SimpleDateFormat fd = new SimpleDateFormat("yyyyMMddHHmmss");
                Calendar calendar = Calendar.getInstance();//此时打印它获取的是系统当前时间
                Long now = Long.valueOf(fd.format(calendar.getTime()).replace("\"", "").trim());//当前系统时间
//    System.out.println("====now=====" + now);
                IPushResult ret = null;
                calendar.add(Calendar.DATE, -1);//当前系统时间 的   前10 小时的时间
                Long tensecondago = Long.valueOf(fd.format(calendar.getTime()).replace("\"", "").trim());
                if (clientId == null || "".equals(clientId) || "null".equals(clientId)) {

                    for (Truck_P_Entity entity : list) {

//        String time = new Timestamp(System.currentTimeMillis()).toString().substring(0,19);
                        Long gpsTime = Long.valueOf(entity.getLastTime().substring(0, 19).replace("-", "").replace(":", "").replace(" ", ""));
//&&entity.getDeptId().equals(deptId)
                        if (entity.getGPSStatus().equals("连接断开") && (gpsTime >= tensecondago) && entity.getDeptId().equals(deptId)) {

                            IGtPush push = new IGtPush(host, appKey, masterSecret);
                            APNTemplate t = new APNTemplate();
                            APNPayload apnpayload = new APNPayload();
                            apnpayload.setSound("");
                            APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
                            //通知文本消息标题
                            alertMsg.setTitle("温馨提示");
                            //通知文本消息字符串
                            alertMsg.setBody(entity.getLastTime() + "您的车辆" + entity.getPlateNo() + "连接断开");
                            //对于标题指定执行按钮所使用的Localizable.strings,仅支持IOS8.2以上版本
                            alertMsg.setTitleLocKey("ccccc");
                            //指定执行按钮所使用的Localizable.strings
                            alertMsg.setActionLocKey("ddddd");
                            apnpayload.setAlertMsg(alertMsg);

                            t.setAPNInfo(apnpayload);
                            ListMessage message = new ListMessage();
                            message.setData(t);
                            String contentId = push.getAPNContentId(appId, message);
                            List<String> dtl = new ArrayList<String>();
                            dtl.add(token);
                            System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
                            ret = push.pushAPNMessageToList(appId, contentId, dtl);
                            System.out.println(ret.getResponse());
//                            return ret.getResponse().toString();
                        }
                    }
                } else {

//    System.out.println("====tensecondago=====" + tensecondago);
                    for (Truck_P_Entity entity : list) {
                        List<Object> query = entityManager.createQuery("select p from PushLog_T_Entity p where p.plateNo =:plateNo and p.deptId =:deptId and p.mobile =:mobile").setParameter("plateNo", entity.getPlateNo()).setParameter("deptId", Integer.valueOf(deptId)).setParameter("mobile", mobile).getResultList();
                        if (CollectionUtils.isEmpty(query)) {
                            //        String time = new Timestamp(System.currentTimeMillis()).toString().substring(0,19);
                            Long gpsTime = Long.valueOf(entity.getLastTime().substring(0, 19).replace("-", "").replace(":", "").replace(" ", ""));
//&&
                            if (entity.getGPSStatus().equals("连接断开") && (gpsTime >= tensecondago) && entity.getDeptId().equals(deptId)) {


                                // 配置返回每个用户返回用户状态，可选
                                System.out.println(entity.getPlateNo());
                                System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
                                IGtPush push = new IGtPush(host, appKey, masterSecret);
                                // 通知透传模板
                                NotificationTemplate template = temp(entityManager, entity.getPlateNo(), entity.getLastTime());
                                ListMessage message = new ListMessage();
                                message.setData(template);
                                // 设置消息离线，并设置离线时间
                                message.setOffline(true);
                                // 离线有效时间，单位为毫秒，可选
                                message.setOfflineExpireTime(24 * 1000 * 3600);
                                // 配置推送目标
                                List targets = new ArrayList();
                                if (clientId.indexOf(",") != -1) {
                                    String[] cid = clientId.split(",");
                                    for (int i = 0; i < cid.length; i++) {
                                        Target target = new Target();
                                        target.setAppId(appId);
                                        target.setClientId(cid[i]);
                                        targets.add(target);
                                    }
                                } else {
                                    Target target = new Target();
                                    target.setAppId(appId);
                                    target.setClientId(clientId);
                                    targets.add(target);
                                }
                                try {
                                    // taskId用于在推送时去查找对应的message
                                    String taskId = push.getContentId(message);
                                    ret = push.pushMessageToList(taskId, targets);
                                    System.out.println(ret.getResponse().toString());
                                    if (ret != null && isPushSuccess(ret)) {
                                        String sqlIn = "insert into pushLog([pushTime],[deptId],[mobile],[plateNo]) values ('" + new Timestamp(System.currentTimeMillis()).toString() + "','" + deptId + "','" + mobile + "','" + entity.getPlateNo() + "')";
                                        entityManager.createNativeQuery(sqlIn).executeUpdate();
                                    }

//                                return ret.getResponse().toString();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    return "服务器异常";
                                }

                            }

                        }

                    }

                }

                if (ret != null && isPushSuccess(ret)) {


                    return "消息推送成功";


                } else {


                    return "无消息推送";

                }


            });
        }, executionContext);
    }


    private boolean isPushSuccess(IPushResult result) {

        if (result.getResponse() != null && result.getResponse().get("result").toString().equals("ok")) {

            return true;

        }

        return false;

    }

    @Override
    public CompletionStage<String> AppPush1() {
        return supplyAsync(() -> {
            return jpaApi.withTransaction(entityManager -> {


                IGtPush push = new IGtPush(appKey, masterSecret, true);
                // 此处true为https域名，false为http，默认为false。Java语言推荐使用此方式
                // IGtPush push = new IGtPush(host, appkey, master);
                // host为域名，根据域名区分是http协议/https协议
                LinkTemplate template = linkTemplateDemo();
                SingleMessage message = new SingleMessage();
                message.setOffline(true);
                // 离线有效时间，单位为毫秒，可选
                message.setOfflineExpireTime(24 * 3600 * 1000);
                message.setData(template);
                message.setPushNetWorkType(0); // 可选，判断是否客户端是否wifi环境下推送，1为在WIFI环境下，0为不限制网络环境。
                Target target = new Target();
                target.setAppId(appId);
                target.setClientId(CID);
                // 用户别名推送，cid和用户别名只能2者选其一
                // String alias = "个";
                // target.setAlias(alias);
                IPushResult ret = null;
                try {
                    ret = push.pushMessageToSingle(message, target);
                } catch (RequestException e) {
                    e.printStackTrace();
                    ret = push.pushMessageToSingle(message, target, e.getRequestId());
                }
                if (ret != null) {

                    System.out.println(ret.getResponse().toString());
                    return "成功";
                } else {

                    System.out.println("服务器响应异常");
                    return "失败";
                }

            });
        }, executionContext);
    }

    
    public static LinkTemplate linkTemplateDemo() {
        LinkTemplate template = new LinkTemplate();
        // 设置APPID与APPKEY
        template.setAppId(appId);
        template.setAppkey(appKey);
        // 设置通知栏标题与内容
        template.setTitle("请输入通知栏标题");
        template.setText("请输入通知栏内容");
        // 配置通知栏图标
        template.setLogo("icon.png");
        // 配置通知栏网络图标，填写图标URL地址
        template.setLogoUrl("");
        // 设置通知是否响铃，震动，或者可清除
        template.setIsRing(true);
        template.setIsVibrate(true);
        template.setIsClearable(true);
        // 设置打开的网址地址
        template.setUrl("http://www.baidu.com");
        return template;
    }

//    public String pushToIos()
//    {
//        IGtPush push = new IGtPush(host, appKey, masterSecret);
//        APNTemplate t = new APNTemplate();
//        APNPayload apnpayload = new APNPayload();
//        apnpayload.setSound("");
//        APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
//        //通知文本消息标题
//        alertMsg.setTitle("aaaaaa");
//        //通知文本消息字符串
//        alertMsg.setBody("bbbb");
//        //对于标题指定执行按钮所使用的Localizable.strings,仅支持IOS8.2以上版本
//        alertMsg.setTitleLocKey("ccccc");
//        //指定执行按钮所使用的Localizable.strings
//        alertMsg.setActionLocKey("ddddd");
//        apnpayload.setAlertMsg(alertMsg);
//
//        t.setAPNInfo(apnpayload);
//        ListMessage message = new ListMessage();
//        message.setData(t);
//        String contentId = push.getAPNContentId(appId, message);
//        System.out.println(contentId);
//        List<String> dtl = new ArrayList<String>();
//        dtl.add(token);
//        System.setProperty("gexin.rp.sdk.pushlist.needDetails", "true");
//        IPushResult ret = push.pushAPNMessageToList(appId, contentId, dtl);
//        System.out.println(ret.getResponse());
//        return ret.getResponse().toString();
//    }


}
